package org.example.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.example.entity.Menu;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.exception.LoginException;
import org.example.service.IMenuService;
import org.example.service.IRoleService;
import org.example.service.IUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Service("UserDetailServiceImpl")
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

    private final IUserService userService;
    private final IRoleService roleService;
    private final IMenuService menuService;

    /**
     * 登录调用的方法
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,username));
        if (user == null) throw new UsernameNotFoundException("用户不存在");
//        获取用户所有的角色
        List<Role> roleList = roleService.listByUserId(user.getUserId());

//        根据角色获取所有菜单
        List<Menu> menuList = menuService.listByRoleIds(roleList.stream().mapToLong(Role::getRoleId).boxed().toArray(Long[]::new));

        Set<String> roleName = roleList.stream().map(Role::getRoleKey).collect(Collectors.toSet());
        Set<String> perms = menuList.stream()
                .filter(menu -> StringUtils.hasText(menu.getPerms()))
                .map(Menu::getPerms).collect(Collectors.toSet());
        UserDetailsImpl userDetails = new UserDetailsImpl();

        userDetails.setRoleKeySet(roleName);
        userDetails.setPermsSet(perms);
        userDetails.setUserName(user.getUserName());
        userDetails.setPassword(user.getPassword());
        userDetails.setStatus(user.getStatus());

        userDetails.setUser(user);
        return userDetails;
    }
}
